<?php

/**
 * ECSHOP 专题前台
 * ============================================================================
 * * 版权所有 2005-2012 上海商派网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * @author:     webboy <laupeng@163.com>
 * @version:    v2.1
 * ---------------------------------------------
 */

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');

if ((DEBUG_MODE & 2) != 2)
{
    $smarty->caching = true;
}

if ($_REQUEST['act'] != 'buy' && strpos($_SERVER['REQUEST_URI'],'.php')!==false){
	jump_404();
}

if (empty($_REQUEST['act']))
{
	$_REQUEST['act'] = 'index';
}


if ($_REQUEST['act'] == 'index')
{
	$templates = 'second.dwt';
	$position = assign_ur_here();
	$smarty->assign('list',get_second_list(1));
	$smarty->assign('start',get_second_list(0));
	$smarty->assign('page_title',       $position['title']);    // 页面标题
	$smarty->assign('ur_here',          $position['ur_here']);  // 当前位置
	$smarty->assign('categories',       get_categories_tree_pro()); // 分类树
	$smarty->assign('helps',            get_shop_help());              // 网店帮助
	assign_template('s',array(1));
	$smarty->assign('cfg', $_CFG);	
}
elseif ($_REQUEST['act'] == 'list')
{
// 	$_REQUEST['id'] = 3;
	if (isset($_REQUEST['id'])){
		$second_id  = intval($_REQUEST['id']);
	}elseif (isset($_REQUEST['sid'])){
		$second_id  = intval($_REQUEST['sid']);
	}else{
		$second_id = 0;
	}
	$topic = get_second_info($second_id);
	if(empty($topic))
	{
		/* 如果没有找到任何记录则跳回到首页 */
		ecs_header("Location: /\n");
		exit;
	}
	
	$templates = 'second_list.dwt';
// 	print_r($topic);

	$topic['data'] = addcslashes($topic['data'], "'");
	$tmp = @unserialize($topic["data"]);
	$tarr = (array)$tmp;

	$goods_id = array();
	$arr = array();
	
	$smarty->assign('min', price_format($topic['min_price']));
	

	$sort_goods_arr = get_second_goods($second_id);
// 	print_r($sort_goods_arr);
	/* 模板赋值 */
	assign_template('s',array(1));
	$position = assign_ur_here();
	$smarty->assign('page_title',       $position['title']);       // 页面标题
	$smarty->assign('ur_here',          $position['ur_here'] . '<span>' . '> ' . $topic['title'].'</span>');     // 当前位置
	$smarty->assign('show_marketprice', $_CFG['show_marketprice']);
	$smarty->assign('goods_list',   $sort_goods_arr);          // 商品列表
	$smarty->assign('topic',            $topic);                   // 专题信息
	$smarty->assign('keywords',         $topic['keywords']);       // 专题信息
	$smarty->assign('description',      $topic['description']);    // 专题信息
	$smarty->assign('helps',      get_shop_help());       // 网店帮助
	$smarty->assign('categories', get_categories_tree()); // 分类树
	$smarty->assign('cfg', $_CFG);
	
	
}
elseif ($_REQUEST['act'] == 'view')
{

	$goods_id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;
	$second_id = isset($_REQUEST['sid']) ? intval($_REQUEST['sid']) : 0;
	if ($second_id <= 0)
	{
		ecs_header("Location: /\n");
		exit;
	}elseif($goods_id <= 0){
		ecs_header("Location: /cuxiao/msqg/list-".$second_id.".html\n");
		exit;
	}

	
	$templates = 'second_goods.dwt';
	

	/* 取得商品信息 */
// 	$goods_id = $second['goods_id'];
	$sql = "SELECT sg.*,g.goods_thumb,g.goods_name,g.shop_price,b.brand_name,g.goods_desc,g.goods_number AS ori_number " .
			"FROM " . $GLOBALS['ecs']->table('second_goods'). " AS sg ".
			"LEFT JOIN " . $GLOBALS['ecs']->table('second') . " AS s ON sg.second_id = s.second_id ".
            "LEFT JOIN " . $GLOBALS['ecs']->table('goods') . " AS g ON sg.goods_id = g.goods_id " .
            "LEFT JOIN " . $GLOBALS['ecs']->table('brand') . " AS b ON g.brand_id = b.brand_id " .
            "WHERE sg.goods_id = '$goods_id' AND sg.second_id = '$second_id' LIMIT 1";
    $goods = $GLOBALS['db']->getRow($sql);
    if (empty($goods))
    {
    	ecs_header("Location: /\n");
    	exit;
    }
    
    $goods['shop_price_format'] =  price_format($goods['shop_price']);
    $goods['goods_thumb']      = get_image_path($goods['goods_id'], $goods['goods_thumb'], true);
    $goods['goods_price_format'] = price_format($goods['goods_price']);
    $goods['jiesheng'] = price_format($goods['shop_price']-$goods['goods_price']); //节省金额
    if($goods['goods_price'] > 0)
    {
    	$goods['zhekou'] = round(10 / ($goods['shop_price'] / $goods['goods_price']), 1);
    }
    else
    {
    	$goods['zhekou'] = 0;
    }
    
    $second = get_second_info($second_id);
    if (empty($second))
    {
    	ecs_header("Location: /\n");
    	exit;
    }
    
    if ($goods['goods_number'] <= 0 || $goods['goods_number'] > $goods['ori_number'])
    {
    	$second['status'] = 3;
    }
    $smarty->assign('second', $second);
    

	/* 读评论信息 */
	$smarty->assign('id',           $goods_id);
	$smarty->assign('type',         0);

	$smarty->assign('goods', $goods);

	/* 取得商品的规格 */
	$properties = get_goods_properties($goods_id);
	$smarty->assign('specification', $properties['spe']); // 商品规格

	//模板赋值
	$smarty->assign('cfg', $_CFG);
	assign_template('s',array(1));
	$position = assign_ur_here(0, $goods['goods_name']);
	$smarty->assign('page_title', $position['title']);    // 页面标题
	$smarty->assign('ur_here',    $position['ur_here']);  // 当前位置
	$smarty->assign('hot_goods',  get_recommend_goods('hot'));     // 最热商品
	$smarty->assign('script_name',  'group');
	$smarty->assign('categories', get_categories_tree()); // 分类树
	$smarty->assign('helps',      get_shop_help());       // 网店帮助
	$smarty->assign('top_goods',  get_top10());           // 销售排行
	$smarty->assign('comment_percent',     comment_percent($goods_id));  //获取评分
	$smarty->assign('', $_CFG['comment_']);
	assign_dynamic();


	$smarty->assign('now_time',  gmtime());           // 当前系统时间

}
elseif ($_REQUEST['act'] == 'buy')
{
	/* 查询：判断是否登录 */
	if ($_SESSION['user_id'] <= 0)
	{
		show_message('您还没有登录，不能参加抢购', '', '/user.php?act=login', 'error');
		exit;
	}

	/* 查询：取得参数：团购活动id */
	$second_id = isset($_POST['second_id']) ? intval($_POST['second_id']) : 0;
	if ($second_id <= 0)
	{
// 		ecs_header("Location: /\n");
		exit;
	}

	/* 查询：取得数量 */
	$number = isset($_POST['number']) ? intval($_POST['number']) : 1;
	$number = $number < 1 ? 1 : intval($number);

	/* 查询：取得活动信息 */
	$second = get_second_info($second_id);
	if (empty($second))
	{
// 		ecs_header("Location: /\n");
		exit;
	}

	/* 查询：检查团购活动是否是进行中 */
	if ($second['status'] == 0)
	{
		show_message('该抢购活动未开始', '', '', 'error');
	}
	elseif ($second['status'] == 2)
	{
		show_message('该抢购活动已结束', '', '', 'error');
	}

	/* 查询：取得商品信息 */
	$goods_id = isset($_POST['goods_id']) ? intval($_POST['goods_id']) : 0;
	$sql = "SELECT sg.*,g.goods_thumb,g.goods_name,g.shop_price,b.brand_name,g.goods_brief,g.goods_number AS ori_number,".
			"g.suppliers_id,g.hs_code,g.goods_sn,g.market_price,g.is_real,g.extension_code,g.tax_price,g.frozen " .
			"FROM " . $GLOBALS['ecs']->table('second_goods'). " AS sg ".
            "LEFT JOIN " . $GLOBALS['ecs']->table('goods') . " AS g ON sg.goods_id = g.goods_id " .
            "LEFT JOIN " . $GLOBALS['ecs']->table('brand') . " AS b ON g.brand_id = b.brand_id " .
            "WHERE sg.goods_id = '$goods_id'";
    $goods = $GLOBALS['db']->getRow($sql);
    if (empty($goods))
    {
//     	ecs_header("Location: /\n");
    	exit;
    }

//     print_r($goods);
	/* 查询：判断数量是否足够 */
    if ($goods['goods_number'] <= 0 || $goods['goods_number'] > $goods['ori_number'] - $goods['frozen'])
    {
    	show_message('该商品已被抢完', '', '', 'error');
		exit;
    }
    
	if ( $number > $goods['goods_number'] )
	{
		show_message('购买的商品数量超过了抢购活动允许的商品购买数量', '', '', 'error');
	}

	/* 查询：取得规格 */
	

	$sql = "SELECT ga.goods_attr_id FROM ".$ecs->table('goods_attr')." AS ga ".
			"LEFT JOIN ".$ecs->table('attribute')." AS a ON a.attr_id=ga.attr_id ".
			"WHERE a.attr_type != 0 AND ga.goods_id='$goods_id'";
	$r = $db->getCol($sql);
	
	if ($r)
	{
		$product_info = get_products_info($goods['goods_id'], $r);
	}
	
	/* 查询：判断指定规格的货品数量是否足够 */
	if (!empty($product_info)  && $number > $product_info['product_number'])
	{
		show_message($_LANG['gb_error_goods_lacking'], '', '', 'error');
		exit;
	}
	
	if (empty($product_info)){
		$product_info = array('product_number' => 0, 'product_id' => 0);
	}
		
	/* 更新：清空购物车中所有秒杀商品 */
	include_once(ROOT_PATH . 'includes/lib_order.php');
// 	clear_cart(CART_SECOND_GOODS);
	
	$goods_attr             = get_goods_attr_info($r);
    $goods_attr_id          = implode(',', $r);



	/* 更新：加入购物车 */
	
	$cart = array(
			'user_id'        => $_SESSION['user_id'],
			'session_id'     => SESS_ID,
			'goods_id'       => $goods['goods_id'],
			'product_id'     => $product_info['product_id'],
			'goods_sn'       => addslashes($goods['goods_sn']),
			'goods_name'     => addslashes($goods['goods_name']),
			'market_price'   => $goods['market_price'],
			'goods_price'    => $goods['goods_price'],
			'goods_number'   => $number,
			'goods_attr'     => addslashes($goods_attr),
			'goods_attr_id'  => $goods_attr_id,
			'is_real'        => $goods['is_real'],
			'extension_code' => addslashes($goods['extension_code']),
			'parent_id'      => 0,
// 			'rec_type'       => CART_SECOND_GOODS,
			'rec_type'		 => CART_GENERAL_GOODS,
			'is_gift'        => 0,
			'suppliers_id'  => $goods['suppliers_id'],
			'hs_code'  => $goods['hs_code'],
			'is_selected'    => 1,
			'goods_tax'		=> $goods['tax_price'],
			'shopping_type'  => 1,	//商品来源：秒杀抢购
			'shopping_type_id' => $second_id
	);
	$db->autoExecute($ecs->table('cart'), $cart, 'INSERT');

	/* 更新：记录购物流程类型：秒杀 */
// 	$_SESSION['flow_type'] = CART_SECOND_GOODS;
// 	$_SESSION['extension_code'] = 'second';
// 	$_SESSION['extension_id'] = $second_id;

	/* 进入收货人页面 */
// 	ecs_header("Location: ./flow.php?step=consignee_new\n");
	ecs_header("Location: ./flow.php\n");
	exit;
}
/* 显示模板 */
$smarty->display($templates);

function get_second_goods($second_id)
{
	if ($second_id<=0) return false;
	$sql = 'SELECT sg.*, g.goods_name, g.shop_price,g.goods_thumb ' .
			'FROM '.$GLOBALS['ecs']->table('second_goods').' AS sg '.
			'JOIN ' . $GLOBALS['ecs']->table('goods') . ' AS g ON sg.goods_id=g.goods_id ' .
			'WHERE sg.second_id = '.$second_id.' AND g.is_real = 1 AND g.is_on_sale = 1 AND g.is_delete = 0 ORDER BY sg.goods_id ';
// 	echo $sql;
	$res = $GLOBALS['db']->query($sql);

	$sort_goods_arr = array();
	
	while ($row = $GLOBALS['db']->fetchRow($res))
	{
	
	
		if ($row['shop_price'] > 0)
		{
			$row['shop_price'] =  price_format($row['shop_price']);
		}
		else
		{
			$row['shop_price'] = '';
		}
	
		$row['url']              = build_uri('second', array('gid'=>$row['goods_id'],'sid'=>$row['second_id']));
		$row['short_name']       = $GLOBALS['_CFG']['goods_name_length'] > 0 ?
		sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name'];
		$row['goods_thumb']      = get_image_path($row['goods_id'], $row['goods_thumb'], true);
		$row['second_price'] = price_format($row['goods_price']);
		
		$sort_goods_arr[] = $row;
	}
	return $sort_goods_arr;
}

function get_second_info($second_id)
{
	$sql = "SELECT s.*,MIN(sg.goods_price) AS min_price  FROM " . $GLOBALS['ecs']->table('second') . "  AS s ".
			"LEFT JOIN ".$GLOBALS['ecs']->table('second_goods')." AS sg ON sg.second_id=s.second_id ".
			" WHERE s.second_id = '$second_id' GROUP BY s.second_id ";
	
	$row = $GLOBALS['db']->getRow($sql);
	
	if(!empty($row))
	{
		$time = gmtime();
		
		if ($row['start_time']>$time){
			$row['status'] = 0; //未开始
		}
		elseif ($row['start_time']<=$time && $time<=$row['end_time']){
			$row['status'] = 1; //进行中
		}
		elseif ($time>$row['end_time']){echo $row['end_time'].' '.$time;
			$row['status'] = 2; //已结束
		}
	}
	
	return $row;

	
	
}

/**
 * 获取正在进行的专题列表
 * @access  public
 * @param int 0未开始，1进行中，2已结束
 * @return void
 */
function get_second_list($type = 0)
{
	$time = gmtime();
	$where = ' WHERE 1=1 ';
	switch ($type){
		case 0:
			$where .= ' AND s.start_time>"'.$time.'"';
			break;
		case 1:
			$where .= ' AND s.start_time<="'.$time.'" AND s.end_time>="'.$time.'"';
			break;
		case 2:
			$where .= ' AND s.end_time<"'.$time.'"';
			break;
	}
    $sql = "SELECT s.*,MIN(sg.goods_price) AS min_price FROM " .$GLOBALS['ecs']->table('second')." AS s ".
      		"LEFT JOIN ".$GLOBALS['ecs']->table('second_goods')." AS sg ON sg.second_id=s.second_id ".
    		$where." GROUP BY s.second_id ORDER BY s.start_time DESC";


    $second = $GLOBALS['db']->getAll($sql);
//     print_r($second);
    $res = array();
	foreach ($second as $k=>$row){
// 		$row['start_time'] = local_date('Y-m-d',$row['start_time']);
// 		$row['end_time']   = local_date('Y-m-d',$row['end_time']);
		$row['url']        = build_uri('second', array('sid'=>$row['second_id']));
		$row['min_price']  = $row['min_price']>0?price_format($row['min_price']):0;
		$res[] = $row;
	}
    
    

    return $res;
}

?>